 class Admins::NewsController < Admins::BaseController

  before_action :set_news, only: [:show, :edit, :update, :destroy,:submit,:approve,:reject,:approve_detail]
  before_action :set_edit_data,only: [:index,:new,:edit,:update,:create]
  before_action :set_seach_data,only: [:index]
  skip_before_filter :authenticate_user!, :verify_authenticity_token,:only => [:uploadify]

  skip_before_action :authenticate_user!, :verify_authenticity_token,:only => [:upload_json]
  # GET /news
  # GET /news.json
  def index
    news_type = params[:news_type] || session[:news_type] || '1'
    @current_user = current_user
    @categories = Category.root - Category.where(:cataname => ['媒体华理','高教纵览','党群连线'])
    @children_cates = (Category.find session[:category_id]).children if (session[:category_id] && session[:category_id] != 0)
    category_id = params[:category_id] if params[:category_id]
    category_id = params[:children_id] if params[:children_id]
    category_id = session[:category_id] if (session[:category_id] && session[:category_id] !=0)
    category_id = session[:children_id] if (session[:children_id] && session[:children_id] !=0)

    department_id = session[:department] if (session[:department] && session[:department] !="")
    @news = News.includes(:category,:sptitles)
              .news_type(news_type,current_user)
            .check(params[:news_check] || session[:news_check]).news_id(params[:news_id] || session[:news_id])
            .writer(params[:news_writer] || session[:news_writer]).category(category_id).sptitle(params[:news_sptitle] || session[:news_sptitle])
            .pubtime(params[:news_begin] || session[:news_begin],params[:news_end] || session[:news_end])
            .contribution_units_id(department_id)
            .all.order("news.created_at desc").page(params[:page])

    @news_count = News.includes(:category,:sptitles)
              .news_type(news_type,current_user)
            .check(params[:news_check] || session[:news_check]).news_id(params[:news_id] || session[:news_id])
            .writer(params[:news_writer] || session[:news_writer]).category(category_id).sptitle(params[:news_sptitle] || session[:news_sptitle])
            .pubtime(params[:news_begin] || session[:news_begin],params[:news_end] || session[:news_end])
            .contribution_units_id(department_id)
            .size
  end

  # GET /news/1
  # GET /news/1.json
  def show

  end




  
  
  
  # GET /news/new
  def new
    if params[:news].blank?
      @news = News.new
    else
      @news = News.new(news_params)
    end
  end


  def change_time
    id = params[:id]
    time =params[:new_time]
    new =News.find_by_id id
    if new
      if new.pubtime
        new.update_attributes(pubtime:Time.parse(time))
      else
        new.update_attributes(created_at:Time.parse(time))
      end
    end
    redirect_to '/admins/news'
  end


  def change_hits
    id = params[:id]
    hits =params[:new_hits]
    
    
    new =News.find_by_id id
    if new && hits.to_i>0
        new.update_attributes(hits:hits)
    end
    redirect_to '/admins/news'
  end
  
  def change_enable
     id = params[:id]
    new =News.find_by_id id
    if new
        new.update_attributes(enable: !new.enable)
    end
    redirect_to '/admins/news'
  end
  
  # GET /news/1/edit
  def edit

  end
  
  


  def uploadify
    file = File.new(params[""])
  end

  # POST /news
  # POST /news.json
  def create
    @news = News.new(news_params.merge({postby: current_user.name}))
    @news.contribution_units = (Department.find news_params[:contribution_units_id]).name unless news_params[:contribution_units_id].blank?
    if @news.is_top == 1
      change_top_new
    end
    @news.editby = current_user.name
    @news.category_id = params[:sec_value] if params[:sec_value].present?
    if @news.save
       unless params[:sptitles].blank?
         sptitles = params[:sptitles]
         sptitles.each do |sp_id|
           NewsSptitle.create(:news_id => @news.id,:sptitle_id => sp_id.to_i)
         end
       end
       unless params[:groups].blank?
         groups = params[:groups]
         admin_group = Group.where(:name => '管理员').first
         groups << admin_group.id unless groups.include?(admin_group.id.to_s)
         groups.each do |group_id|
           NewsGroup.create(:news_id => @news.id,:group_id => group_id.to_i)
         end
       end
       redirect_to :action => :index, notice: '稿件创建成功.'
    else
        flash[:error] = @news.errors.full_messages.join(",")
        render 'new'
    end
  end

  def submit
    @news = News.find(params[:id])
    
    if @news.commit=0
       @news.commitime = Time.now
       @news.commit = 1
     end 
   
    respond_to do |format|
      if @news.update_attributes(check: 1)
        format.html { redirect_to :action => :index, notice: '稿件送审成功.' }
      else
        format.html { render :edit }
      end
    end
  end

  #采用
  def approve
    if current_user.admin? # 只有管理员才改时间。。。
      if @news.audit=0
       @news.pubtime = Time.now
       @news.audit = 1
     end 
     end
     
    @news.update_attributes(check: 2)
    group = current_user.groups.first
    @news.news_groups.where(:group_id => group.id).first.update_attributes(:check => 1)
    @news.update_attributes(aprroved_count: @news.aprroved_count+1)
    @news.update_attributes(editby: current_user.name)
    redirect_to admins_news_index_url @news, notice: '稿件采用成功.'
  end

  #不采用
  def reject
    @news.update_attributes(check: 3)
    group = current_user.groups.first
    @news.news_groups.where(:group_id => group.id).first.update_attributes(:check => 2,:reason => params[:reason])
    @news.update_attributes(toback_count: @news.toback_count+1,check: 1) #原来check: 0
    redirect_to admins_news_index_url @news, notice: '稿件退回成功.'
  end

  #稿件采用详情
  def approve_detail

  end

  # PATCH/PUT /news/1
  # PATCH/PUT /news/1.json
  def update
    contribution_units = (Department.find news_params[:contribution_units_id].to_i).name unless news_params[:contribution_units_id].blank?
    if news_params[:is_top].present? && news_params[:is_top].to_i == 1
      change_top_new
    end
    respond_to do |format|
       p (Department.find news_params[:contribution_units_id].to_i).name 
       p 123 unless news_params[:contribution_units_id].blank?
       p (Department.find news_params[:contribution_units_id].to_i).name unless news_params[:contribution_units_id].blank?
       
      if @news.update(news_params)
        @news.update_attributes(contribution_units:contribution_units)
        if (!current_user.admin? )
         @news.update_attributes(check: 0)
         else
             @news.update_attributes(check: 1)
         
        end



 
       @news.update_attributes(:category_id => params[:sec_value]) if params[:sec_value].present?
        NewsSptitle.where(:news_id => @news.id).delete_all
        unless params[:sptitles].blank?
          sptitles = params[:sptitles]
          sptitles.each do |sp_id|
            NewsSptitle.create(:news_id => @news.id,:sptitle_id => sp_id.to_i)
          end
        end
        unless params[:groups].blank?
          NewsGroup.where(:news_id => @news.id).delete_all
          groups = params[:groups]
          admin_group = Group.where(:name => '管理员').first
          groups << admin_group.id unless groups.include?(admin_group.id.to_s)
          groups.each do |group_id|
            NewsGroup.create(:news_id => @news.id,:group_id => group_id.to_i)
          end
        end
        format.html { redirect_to :action => :index, notice: '稿件更新成功.' }
      else
        flash[:error] = @news.errors.full_messages.join(",")
        format.html { render :edit }
      end
    end
  end


  def confirm_check
    respond_to do |format|
      change_new_check params[:id]
      format.html { redirect_to :action => :index, notice: '稿件送审成功.' }
    end
  end


  # DELETE /news/1
  # DELETE /news/1.json
  def destroy
    @news.destroy
    respond_to do |format|
      format.html { redirect_to admins_news_index_url(), notice: '稿件成功删除.' }
      format.json { head :no_content }
    end
  end

  def get_second_categories
    cate_id = params[:cate_id]
    if cate_id.blank?
      second_categories = []
    else
      second_categories = Category.where(:father => cate_id)
    end
    render :json => second_categories.to_json,:layout => false
  end
#上传图片
  def upload_json
    tmp = params[:imgFile]
    postfix_name =tmp.original_filename.split('.')[-1]
    postfix_name =postfix_name.downcase
    root_path = Rails.root.to_s
    file_name = "#{Time.now.to_i.to_s}#{(10000+rand(90000)).to_s}.#{postfix_name}"
    path_zip = "#{root_path}/public/UploadFile/DES/#{Date.today.year}"
    path_ori = "#{root_path}/public/UploadFile/SOU/#{Date.today.year}"
    full_path_zip ="#{path_zip}/#{file_name}"
    full_path_ori = "#{path_ori}/#{file_name}"
    @img_resources=%w[jpg png gif jpeg  bmp]
    @lim_resource=%w[zip jpg jpeg png mp3 wma  mp4  3gp gif swf js css rm rmvb flv wmv]
    @img_resources=%w[jpg png gif jpeg]
    @voice_resources=%w[mp3 wma wav]   #音频
    @video_resoures=%w[mp4 3gp swf rm rmvb flv wmv] #视频
    @file_resoures=%w[content  ]
    if @img_resources.include?(postfix_name) && tmp.size<200*1024*1024
      p "print ==============================",tmp,full_path_ori,path_ori
      svae_afile tmp,full_path_ori,path_ori
      min_image full_path_ori,full_path_zip,path_zip
      {error:0,url:"/UploadFile/DES/#{Date.today.year}/#{file_name}"}
      hash = {error:0,url:"/UploadFile/DES/#{Date.today.year}/#{file_name}"}
      p 22222222222222222,hash
    elsif @voice_resources.include?(postfix_name) && tmp.size<200*1024*1024
      svae_afile tmp,full_path_ori,path_ori
      hash = {error:0,url:"/UploadFile/SOU/#{Date.today.year}/#{file_name}"}
    elsif @video_resoures.include?(postfix_name) && tmp.size<200*1024*1024
      svae_afile tmp,full_path_ori,path_ori
      hash = {error:0,url:"/UploadFile/SOU/#{Date.today.year}/#{file_name}"}
    else
      hash = {error:1,url:"上传资源不超过200M"}
    end
    render json:hash
  end

  #资源全路径,文件名 ,dir
  def min_image(full_path_ori,file_path,path_ori)
    FileUtils.mkdir_p path_ori unless File.exists?(path_ori)
     if !File.exist?(file_path)
       p 11111111, full_path_ori
        FileUtils.chmod(0777,File.new(full_path_ori))
       image = MiniMagick::Image.open(full_path_ori)
       if image.width > 800
         image.resize "800"
         image.write  file_path
       else
         image.write  file_path
       end

     end
    FileUtils.chmod(0777,File.new(file_path))

  end
  ######### 保存一个文件
  def svae_afile(tmp,full_path,path_zip)
    FileUtils.mkdir_p path_zip unless File.exists?(path_zip)
    save tmp,full_path
  end
  #保存单个文件
  def save tmp,full_path
    #file = File.join("public",@tmp.original_filename)
    #dirname=Rails.root.to_s+SITE_PATH % @root_path+"//resources"
     #FileUtils.chmod(0777,File.new(full_path))
    file1=File.new(full_path, 'wb')  

   #file1.chmod(0777)
    #FileUtils.chmod(0777,File.new(full_path))
   # Process.exec("chmod 777  #{full_path}")
    FileUtils.cp tmp.path,full_path

  end
  private
  #更新稿件的时候，更新状态
  def change_new_check new_id
    news = NewsGroup.where(news_id:new_id)
    flag = false
    p "===============]#{news}"
    if news.blank?
    else
      news.each do |new|
        if new.check==2
          new.update_attributes(check:nil)
        end
      end
    end
  end
  # Use callbacks to share common setup or constraints between actions.
  def set_news
    @news = News.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def news_params
    params.require(:news).permit(:title, :bottomtitle, :uptitle, :author_name, :cameraman_name,
                                 :phone, :contribution_units, :contribution_units_id, :body,
                                 :is_important_news,:keywords,:home_page_image,:writer,:category_id,
                                  :yaowen_title,:is_top,:toutiao_content,:commit,:commitime,:audit ,:enable)
  end

  def set_edit_data
    @categories = (Category.where(:father => 0) - Category.where(:cataname => ['媒体华理','党群连线','高教纵览','视听资讯']))
    @sptitles = Sptitle.all
    @groups = Group.all.where(:name => ['管理员','校报组','外宣组'])
    @departments = Department.all
  end

  def set_seach_data
    session[:news_type] = params[:news_type] if params[:news_type]
    session[:news_check] = params[:news_check] if params[:news_check]
    session[:news_writer]= params[:news_writer] if params[:news_writer]
    session[:category] = params[:category] if params[:category]
    session[:department] = params[:department] if params[:department]
    session[:news_begin] = params[:news_begin] if params[:news_begin]
    session[:news_end] = params[:news_end] if params[:news_end]
    session[:category_id] = params[:category_id].to_i if params[:category_id]
    session[:children_id] = params[:children_id].to_i if params[:children_id]
    session[:news_sptitle] = params[:news_sptitle] if params[:news_sptitle]
    session[:news_id] = params[:news_id] if params[:news_id]
  end

  def change_top_new
      top_new = News.where(:is_top => 1).first
      if top_new
        top_new.is_top = 0
        top_new.save
      end
  end
end
